//
//  SearchTextTimeViewController.m
//  XTCloud
//
//  Created by QA on 2017/9/5.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "SearchTextTimeViewController.h"
#import "GETableView.h"

#import "GEInputTableViewCell.h"
#import "MTCSelectClienterViewController.h"
#import "MTCConcreteConfirmationViewController.h"
#import "SearchTextTimeViewCell.h"

#import "NSDictionary+DataFormat.h"
#import "NSMutableDictionary+Format.h"
#import "GEPickerTextField.h"
#import "NSMutableArray+Format.h"
#import "GEWeekTimeFromatter.h"
#import "GEDateFromatter.h"
#import "SearchTagEntity+CoreDataClass.h"

@interface SearchTextTimeViewController ()<TTGTextTagCollectionViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *orderInfo;
@property (nonatomic,strong) IBOutlet GETableView *tableView;

@end

@implementation SearchTextTimeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"数据筛选"];
        //设置搜索按钮
        UIButton* righButtont= [UIButton buttonWithType:UIButtonTypeCustom];
        righButtont.frame = CGRectMake(0, 0, 44, 44);
        [righButtont setTitle:@"确定" forState:UIControlStateNormal];
        [righButtont addTarget:self action:@selector(searchTextInfoSelector:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:righButtont];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchTextInfoSelector:(id)sender
{
    UITextField *textField01 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    UITextField *textField02 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
    UITextField *textField03 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:2 inSection:0];
    
    //保存关键字到数据库
    if(textField01.text && textField01.text.length >0){
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"content = %@", textField01.text];
        NSArray *array = [SearchTagEntity MR_findAllWithPredicate:predicate];
        //判断关键字是否存在
        if(array <=0){
            SearchTagEntity *entity = [SearchTagEntity MR_createEntity];
            entity.content = textField01.text;
            entity.createTime = [NSDate date];
            //保存数据成功并回执
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        }
    }
    
    //搜索返回
    if (self.backResultDelagate && [self.backResultDelagate respondsToSelector:@selector(backResultDataKey:dataValue:)]) {
        NSArray *array = @[textField01.text,textField02.text,textField03.text];
        [self.backResultDelagate backResultDataKey:self.key dataValue:array];
    }
    [super backButtonEvent:nil];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0) return 3;
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"CreateContractViewController%ld%ld",indexPath.section,indexPath.row];
    
    //按天数
    if(indexPath.section == 0){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell != nil) return cell;
        
        if(indexPath.row == 0){
            cell = [[GEInputTableViewCell alloc] initWithReuseIdentifier:CellIdentifier model:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"筛选条件";
            cell.placeholder = @"请输入搜索关键字";
            [cell setEnablePrevious:NO next:NO];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            
        } else if(indexPath.row == 1){
            cell = [[GEInputTableViewCell alloc] initWithDateReuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"起始日期";
            cell.placeholder = @"请选择起始日期";
            cell.isMark = YES;
            [cell setEnablePrevious:NO next:NO];
            [cell setDatePickerMode:UIDatePickerModeDate];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        } else if(indexPath.row == 2){
            cell = [[GEInputTableViewCell alloc] initWithDateReuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"截止日期";
            cell.placeholder = @"请选择截止日期";
            cell.isMark = YES;
            [cell setEnablePrevious:NO next:NO];
            [cell setDatePickerMode:UIDatePickerModeDate];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        }
        return cell;
    }
    
    //按天数
    if(indexPath.section == 1){
        NSArray *allTags = @[@"今日", @"本周", @"本月", @"本季度", @"本年"];
        SearchTextTimeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) cell = [[SearchTextTimeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.tagsView.delegate = self;
        cell.tagsView.tag = 1;
        
        [cell setTags:allTags];
        return cell;
    }
    
    //历史搜索关键字
    if(indexPath.section == 2){
        NSMutableArray *allTags = [NSMutableArray array];
        NSArray *array = [SearchTagEntity MR_findAll];
        for(SearchTagEntity *entity in array) [allTags addObject:entity.content];

        SearchTextTimeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) cell = [[SearchTextTimeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.tagsView.delegate = self;
        cell.tagsView.tag = 2;
        
        [cell setTags:allTags];
        return cell;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 44;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //键盘事件处理
    UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:indexPath.row inSection:indexPath.section];
    if (textField) [textField becomeFirstResponder];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section==0) return 10;
    else return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 30)];
    view.backgroundColor = [UIColor clearColor];
    if(section == 0) return view;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 29.5)];
    //lable.textColor = ThemeColorBlue;
    lable.textColor = [UIColor colorWithWhite:0.25 alpha:1];
    lable.backgroundColor = [UIColor whiteColor];
    lable.font = [UIFont boldSystemFontOfSize:14];
    [view addSubview:lable];
    
    if(section == 2){
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SuperWidth - 55, 0, 46, 29.5);
        [button setImage:[UIImage imageNamed:@"camera_delete"] forState:UIControlStateNormal];
        [button setImageEdgeInsets:UIEdgeInsetsMake(3, 10, 3, 10)];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        button.titleLabel.textAlignment = NSTextAlignmentRight;
        [view addSubview:button];
        [button addTarget:self action:@selector(deleteSelector:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if(section == 1){
        lable.text = @"  快捷时间段";
    } else if(section == 2){
        lable.text = @"  历史搜索关键字";
    }
    return view;
}


#pragma mark
#pragma mark - TTGTextTagCollectionViewDelegate

- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView didTapTag:(NSString *)tagText atIndex:(NSUInteger)index selected:(BOOL)selected
{
    //快捷时间段
    if(textTagCollectionView.tag == 1){
        [self setPeriodTimeIndex:index];
    }
    
    //历史搜索关键字
    else if(textTagCollectionView.tag == 2){
        UITextField *textField01 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
        textField01.text = tagText;
    }
}

- (void)setPeriodTimeIndex:(NSUInteger)index
{
    UITextField *textField02 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
    UITextField *textField03 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:2 inSection:0];
    
    //今日
    if(index == 0){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateAndTime =  [dateFormatter stringFromDate:[NSDate date]];
        textField02.text = dateAndTime;
        textField03.text = dateAndTime;
    }
    
    //本周
    else if(index == 1){
        NSDate *now = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit fromDate:now];
        
        // 得到星期几
        // 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
        NSInteger weekDay = [comp weekday];
        NSInteger day = [comp day];
        
        // 计算当前日期和这周的星期一和星期天差的天数
        long firstDiff,lastDiff;
        if (weekDay == 1) {
            firstDiff = 1;
            lastDiff = 0;
        } else{
            firstDiff = [calendar firstWeekday] - weekDay;
            lastDiff = 9 - weekDay;
        }
        
        // 在当前日期(去掉了时分秒)基础上加上差的天数
        NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
        [firstDayComp setDay:day + firstDiff + 1];
        NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];
        
        NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
        [lastDayComp setDay:day + lastDiff];
        NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];
        
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy-MM-dd"];
        
        textField02.text = [formater stringFromDate:firstDayOfWeek];
        textField03.text = [formater stringFromDate:now];
        //NSLog(@"星期一开始 %@",[formater stringFromDate:firstDayOfWeek]);
        //NSLog(@"当前 %@",[formater stringFromDate:now]);
        //NSLog(@"星期天结束 %@",[formater stringFromDate:lastDayOfWeek]);
    }
    
    //本月
    else if(index == 2){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM"];
        NSString *dateAndTime =  [dateFormatter stringFromDate:[NSDate date]];
        textField02.text = [NSString stringWithFormat:@"%@-01",dateAndTime];
        
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateFormat:@"yyyy-MM-dd"];
        NSString *dateAndTime1 =  [dateFormatter1 stringFromDate:[NSDate date]];
        textField03.text = dateAndTime1;
    }
    
    //本季度
    else if(index == 3){
        NSDate *date = [NSDate date];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        comps = [calendar components:unitFlags fromDate:date];
        
        NSInteger year=[comps year];
        NSInteger month=[comps month];
        NSInteger quarter = (month/3) + (month%3!=0 ? 1:0);
        if(quarter == 1){//一季度
            textField02.text = [NSString stringWithFormat:@"%ld-01-01",year];
            textField03.text = [NSString stringWithFormat:@"%ld-03-31",year];;
        } else if(quarter == 2){//二季度
            textField02.text = [NSString stringWithFormat:@"%ld-04-01",year];
            textField03.text = [NSString stringWithFormat:@"%ld-06-30",year];;
        } else if(quarter == 3){//三季度
            textField02.text = [NSString stringWithFormat:@"%ld-07-01",year];
            textField03.text = [NSString stringWithFormat:@"%ld-09-30",year];;
        } else if(quarter == 4){//四季度
            textField02.text = [NSString stringWithFormat:@"%ld-10-01",year];
            textField03.text = [NSString stringWithFormat:@"%ld-12-31",year];;
        }
    }
    
    //本年
    else if(index == 4){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy"];
        NSString *dateAndTime =  [dateFormatter stringFromDate:[NSDate date]];
        textField02.text = [NSString stringWithFormat:@"%@-01-01",dateAndTime];
        
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateFormat:@"yyyy"];
        NSString *dateAndTime1 =  [dateFormatter1 stringFromDate:[NSDate date]];
        textField03.text = [NSString stringWithFormat:@"%@-12-31",dateAndTime1];
    }
}


#pragma mark
#pragma mark - Button Event

//删除历史搜索关键字
- (void)deleteSelector:(id)selector
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"确定清空历史关键字吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //清空历史记录
    if(buttonIndex == 1){
         NSArray *persons = [SearchTagEntity MR_findAll];
         for(SearchTagEntity *model in persons) [model MR_deleteEntity];
        //保存数据成功并回执
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        [self.tableView reloadData];
    }
}


@end
